#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File    :   user.py
@Time    :   2020/09/22 11:04:07
@Author  :   fengzhilaoling 
@Version :   1.0
@Contact :   fengzhilaoling@163.com
'''
from flask import Blueprint
from flask import request
from flask import render_template
from models.models import User
from exts import db
from flask import render_template_string
from flask import jsonify
from flask import url_for
from flask import redirect
from flask import session

user_bp = Blueprint('user', __name__)


@user_bp.route('/login/', methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        return render_template('login.html')
    elif request.method == 'POST':
        user_name = request.form.get('user_name')
        pwd = request.form.get('pwd')
        result = User.query.filter(User.u_name == user_name).first()
        if result:
            if result.check_password(pwd):
                # session['user'] = user_name
                # session['login_status'] = 1
                return render_template_string('登陆成功！')
        data = {
            'info_user': '用户名或密码错误！'
        }
        return render_template('login.html', **data)


@user_bp.route('/add/', methods=['GET', 'POST'])
def add():
    if request.method == 'GET':
        return render_template('add.html')
    elif request.method == 'POST':
        user_name = request.form.get('user_name')
        pwd = request.form.get('pwd')
        user = User(id=None, u_name=user_name, password=pwd)
        db.session.add(user)
        db.session.commit()
        return redirect(url_for('user.login'))


@user_bp.route('/check/')
def check():
    user_name = request.args.get('user_name')
    result = User.query.filter(User.u_name == user_name).first()
    if result:
        return jsonify({'startus': True})
    else:
        return jsonify({'startus': False})
